package com.pospi.xstore.ui.caigou;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.R;
import com.pospi.xstore.dto.CustomerBeen;
import com.pospi.xstore.dto.StoreBeen;
import com.pospi.xstore.dto.SupBeen;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.SaveOrderInfo;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/*
* 采购订单
* */

public class SearchRefundBillActivity extends BaseActivity {
//    @Bind(R.id.bt_today)
//    Button bt_today;
//    @Bind(R.id.bt_ystoday)
//    Button bt_ystoday;
//    @Bind(R.id.switch_button)
//    SwitchMultiButton switch_button;
    @Bind(R.id.time_start_select)
    TextView time_start_select;
    @Bind(R.id.time_end_select)
    TextView time_end_select;
    @Bind(R.id.djbh)
    EditText bill_no;
    @Bind(R.id.cgmd)
    TextView tv_shop;
    @Bind(R.id.gys)
    TextView tv_sup;
    @Bind(R.id.status_bill)
    TextView status_bill;
    String[] data = new String[]{"1号门店", "2号门店", "3号门店", "4号门店"};
    String[] data2 = new String[]{"审核", "未审核"};
    private List<CgddBeen> cgddBeens = new ArrayList<>();
    private List<StoreBeen> storeBeens;
    private List<CustomerBeen> customerBeens;
    private CustomerBeen customerBeen = new CustomerBeen();
    private SupBeen supBeen = new SupBeen();
    private String stutas = "";
    private String count;
    private String je;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.abtivity_cgdd);
        ButterKnife.bind(this);
        setTitle("采购退厂单查询");

        time_start_select.setText(GetData.getYYMMDDTime());
        time_end_select.setText(GetData.getYYMMDDTime());
//        switch_button.setText("今天","昨天","近三天");
//        switch_button.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
//            @Override
//            public void onSwitch(int position, String tabText) {
//                switch (position) {
//                    case 0:
//                        time_start_select.setText(GetData.getYYMMDDTime());
//                        time_end_select.setText(GetData.getYYMMDDTime());
//                        break;
//                    case 1:
//                        time_start_select.setText(GetData.getAnyTime(1));
//                        time_end_select.setText(GetData.getYYMMDDTime());
//                        break;
//                    case 2:
//                        time_start_select.setText(GetData.getAnyTime(3));
//                        time_end_select.setText(GetData.getYYMMDDTime());
//                        break;
//                }
//            }
//        });

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        SupBeen been = (SupBeen) intent.getSerializableExtra("sup");
        if (been != null) {
            tv_sup.setText(been.getName());
            supBeen = been;
        }

    }



    List<String> strings = new ArrayList<>();
    @OnClick({R.id.cgmd,R.id.gys,R.id.status_bill,R.id.bt_search,R.id.time_start_select,R.id.time_end_select})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cgmd:
                storeBeens = SaveOrderInfo.changeStoreToList(SPHelper.getInstance().getString(Constant.STORE_LIST));
                strings.clear();
                for (StoreBeen been : storeBeens) {
                    strings.add(been.getName());
                }
                creatDialog(strings);

                break;
            case R.id.gys:
                Intent intent = new Intent(this, SupActivity.class);
                intent.putExtra("mark", "SearchRefundBillActivity");
                startActivity(intent);
                break;
            case R.id.status_bill:
                creatDialog2(data2);
                break;
            case R.id.bt_search:
                searchBill(cgddBeen.getBillno(),supBeen.getId(),cgddBeen.getMarket(),stutas);
                break;
            case R.id.time_start_select:
                TimePickerDialog dialogYearMonthDay = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("选择日期")
                        .setWheelItemTextSize(16)
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                Date date = new Date(millseconds);
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                                String time = format.format(date);
                                time_start_select.setText(time);
                            }
                        })
                        .build();
                dialogYearMonthDay.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;
            case R.id.time_end_select:
                TimePickerDialog dialogYearMonthDay2 = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("选择日期")
                        .setWheelItemTextSize(16)
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                Date date = new Date(millseconds);
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                                String time = format.format(date);
                                time_end_select.setText(time);
                            }
                        })
                        .build();
                dialogYearMonthDay2.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;
//            case R.id.bt_threeday:
//
//                break;
        }
    }


    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    Intent intent = new Intent(SearchRefundBillActivity.this,RefundBillListActivity.class);
                    intent.putExtra("cgdd_info", (Serializable) cgddBeens);
                    intent.putExtra("count", count);
                    intent.putExtra("je", je);
                    startActivity(intent);
                    break;
                case 2:

                    break;
                case 3:

                    break;
                case 4:

                    break;
            }

        }
    };
    private void searchBill(String billno,String supid,String market,String status) {
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", Constant.BILL_MODE_CGTC);
        params.put("type", Constant.BILL_TYPE_CGTC);
        params.put("fun", "find_list");

//        params.put("page", "");
//        params.put("limit", "");


        JSONObject object = new JSONObject();
        try {
            object.put("startrq", time_start_select.getText().toString().trim());
            object.put("endrq", time_end_select.getText().toString().trim());
            object.put("billno", billno);
            object.put("market", market);
            object.put("supid", supid);
            object.put("num", "");
            object.put("barcode", "");
            object.put("status", status);
//            object.put("filter", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login",params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    Log.i("login", jsonObject.getString("errMsg"));
                    cgddBeens = new Gson().fromJson(result.toString(),
                            new TypeToken<List<CgddBeen>>() {
                            }.getType());
                    JSONObject sumrow = jsonObject.getJSONObject("sumrow");
                    count = sumrow.getString("count");
                    je = sumrow.getString("je");
                    Message message = Message.obtain();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }

    private CgddBeen cgddBeen = new CgddBeen();
    private void creatDialog(List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //门店
                        tv_shop.setText(storeBeens.get(i).getName());

                        cgddBeen.setMarket(storeBeens.get(i).getId());
                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }
    private void creatDialog2(final String[] ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //
                        status_bill.setText(ss[i]);
                        switch (ss[i]) {
                            case "审核":
                                stutas = "2";
                                break;
                            case "未审核":
                                stutas = "1";
                                break;
                        }
                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }

}
